import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { removeUser } from '@/utils/auth' 
// create an axios instance
const service = axios.create({
  baseURL: null,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // if (store.getters.token) {
    //   config.headers['token'] = getToken()
    // }
    return config
  },
  error => { 
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {    
    if (response.status === 200) {
      const res = response.data
      //&& router.currentRoute.path !== '/login'
      if (res.status == 403) {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 3 * 1000
        }) 
        setTimeout(()=>{
          globalVue.$router.push('/frontmsg/recharge'); 
        },3000);  
        // return Promise.reject(res)
      } else { 
        return res
      } 
    }  else {  
      return Promise.reject(response)
    }
  },
  error => {  
    if(error.response.status==401){
      Message({
        message:"登录超时，请重新登录",
        type: 'error',
        duration: 3 * 1000
      })  
      removeUser();//移除本地用户信息
      setTimeout(()=>{
        globalVue.$router.push('/login/first');  
      },3000); 
    }else{ 
      Message({
        message: '后台服务报500错误:'+error,
        type: 'error',
        duration: 3 * 1000
      })  
    }  
    return Promise.reject(error)
  }
)

export default service
